<template>
  <div class="data-chart-container">
    <!-- 顶部控制区域 -->
    <div class="control-panel">
      <!-- Checkbox 群改为下拉菜单 -->
      <el-dropdown class="dropdown-control" trigger="click">
        <span class="el-dropdown-link">
          <el-button type="primary" size="small" :icon="Filter">
              {{ t('datacenter.iotdataPage.paramSelection') }}
            </el-button>
        </span>
        <template #dropdown>
          <el-dropdown-menu class="checkbox-dropdown">
            <el-dropdown-item>
              <el-checkbox
                v-model="allSelected"
                :indeterminate="isIndeterminate"
                @change="handleAllChange"
                :label="t('datacenter.iotdataPage.selectAll')"
              ></el-checkbox>
            </el-dropdown-item>
            <!-- 修复：移除外部el-dropdown-item，直接放置checkbox-group -->
            <el-checkbox-group v-model="selectedColumns" class="vertical-checkbox-group">
              <el-checkbox
                v-for="item in columns"
                :key="item.val"
                :label="item.val"
                @change="handleItemChange"
                class="vertical-checkbox-item"
              >
                {{ item.label }}
              </el-checkbox>
            </el-checkbox-group>
          </el-dropdown-menu>
        </template>
      </el-dropdown>

      <!-- 列数选择改为下拉菜单 -->
      <el-dropdown class="dropdown-control" trigger="click">
        <span class="el-dropdown-link">
          <el-button type="primary" size="small" :icon="Grid">
            {{ columnCount }}{{t('buttons.columns')}}
          </el-button>
        </span>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item @click="columnCount = 1">1{{t('buttons.columns')}}</el-dropdown-item>
        <el-dropdown-item @click="columnCount = 2">2{{t('buttons.columns')}}</el-dropdown-item>
        <el-dropdown-item @click="columnCount = 3">3{{t('buttons.columns')}}</el-dropdown-item>
        <el-dropdown-item @click="columnCount = 4">4{{t('buttons.columns')}}</el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </div>

    <!-- 卡片区域 -->
    <div
      v-if="total > 0"
      class="cards-container"
      :style="{ gridTemplateColumns: `repeat(${columnCount}, 1fr)` }"
    >
      <el-card
        v-for="param in selectedColumnsMap"
        :key="param.val"
        class="data-card"
      >
        <template #header>
          <div class="card-header">
            <span class="card-title">{{param.label + "("+ param.unit + ")"}}</span>
            <el-button
              type="text"
              icon="el-icon-setting"
              size="small"
              @click="(e) => {
                e.stopPropagation();
                openSettingDialog(param);
              }"
            ></el-button>
          </div>
        </template>
        <!-- 卡片内容区域，可以根据实际需求添加图表或其他内容 -->
        <div class="card-content">
          <!-- 这里可以放图表或其他数据展示组件 -->
            <div class="chart-container">
              <AeEchartLine
                :title="''"
                :xAxisUnit="'Time'"
                :xAxisType="'category'"
                :xAxisData="timeArray"
                :yAxisUnit="param.unit"
                :seriesData="generateSeriesData(param.val)"
                :showToolbar="true"
                :showZoom="true"
                @pointClick="handlePointClick"
              />
            </div>

        </div>
      </el-card>
    </div>
    <el-empty v-if="total == 0" :description="t('datacenter.iotdataPage.noData')" />

    <!-- 设置弹窗 -->
    <el-dialog
      v-model="settingDialogVisible"
      :title="`${currentParam?.name || t('datacenter.iotdataPage.param')}${t('datacenter.iotdataPage.setting')}`"
      width="500px"
    >
      <div v-if="currentParam" class="setting-form">
        <el-form label-width="120px">
          <el-form-item :label="t('datacenter.iotdataPage.paramName')">
            <el-input v-model="currentParam.name" disabled></el-input>
          </el-form-item>
          <el-form-item :label="t('datacenter.iotdataPage.paramProp')">
            <el-input v-model="currentParam.prop" disabled></el-input>
          </el-form-item>
          <!-- 这里可以添加更多设置项 -->
          <el-form-item :label="t('datacenter.iotdataPage.displayColor')">
            <el-color-picker v-model="currentParam.color"></el-color-picker>
          </el-form-item>
          <el-form-item :label="t('datacenter.iotdataPage.dataUnit')">
            <el-input v-model="currentParam.unit"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="settingDialogVisible = false">{{ t('datacenter.iotdataPage.cancel') }}</el-button>
          <el-button type="primary" @click="saveSettings">{{ t('datacenter.iotdataPage.confirm') }}</el-button>
        </div>
      </template>
    </el-dialog>


    <!-- 波形抽屉组件 -->
    <drawer-ae-wave-card
      v-model:visible="showDrawer"
      :product-key="currentRow.productKey"
      :device-no="currentRow.deviceNo"
      :sampletime="currentRow.sampletime"
      :deviceOptions="deviceOptions"
    />

  </div>
</template>

<script setup lang="ts">
// 导入所需图标
import { Filter, Grid } from '@element-plus/icons-vue';
import { ref, computed, watch, reactive, toRaw } from "vue";
import { ElMessage } from 'element-plus';
import AeEchartLine from '@/views/components/aecharts/AeEchartLine.vue';
import DrawerAeWaveCard from "@/views/components/aewave/drawerAeWaveCard.vue";
import { pageSizeOptions } from "@/utils/appCommon/appCommonOptions/app";
import { getRandomColor } from "@/utils/appCommon/colorUtil";
import { useI18n } from "vue-i18n";

// 控制抽屉显示/隐藏
const showDrawer = ref(false);
const {t} = useI18n();

const props = defineProps({
  params: {
    type: Object,
    required: true
  },
  columns: {
    type: Array,
    required: true
  },
  data: {
    type: Array,
    required: true
  },
  total: {
    type: Number,
    required: true
  },
  deviceOptions: {
    type: Array,
    required: false,
    default: [],
  }
});
const emit = defineEmits(['onPageChange']);
const currentRow = ref({
  productKey: props.params.productKey,
  deviceNo: "",
  sampletime: 0,
});

const columns = ref(props.columns);
const iotData = ref(props.data);

// 获取所有时间点的一维数组
const timeArray = computed(() => {
  const res =  [...new Set(iotData.value.map(item => item.sampletime ?item.sampletime: 0))];
  return res
});

// 按设备编号分组的数据
const groupedByDevice = computed(() => {
  const groups = {};
  const allTimes = [...new Set(iotData.value.map(item => item.sampletime))];

  iotData.value.forEach((item:any) => {
    if (!groups[item.deviceNo]) {
      // 初始化设备数据，为所有时间点创建空位置
      groups[item.deviceNo] = allTimes.map(time => ({
        sampletime: time,
        deviceNo: item.deviceNo,
        ...Object.fromEntries(Object.keys(item)
          .filter(key => key !== 'sampletime' && key !== 'deviceNo')
          .map(key => [key, null]))
      }));
    }

    // 更新实际存在的数据
    const timeIndex = allTimes.indexOf(item.sampletime);
    if (timeIndex !== -1) {
      groups[item.deviceNo][timeIndex] = item;
    }
  });

  return groups;
});

// 生成图表数据
const generateSeriesData = (paramVal:any) => {
  const res = Object.entries(groupedByDevice.value).map(([deviceNo, items], index:number) => {
    return {
      name: deviceNo,
      data: items.map((item:any) => item[paramVal]),
      color: getRandomColor(index),
      connectNulls: true ,  // 不相邻的点能连接起来
    };
  });
  return res
};
const total = ref(props.total);
const pageSizeOps = ref(pageSizeOptions)

// 内部状态
const selectedColumns = ref<string[]>(columns.value.map(col => col.val));
const allSelected = ref(false);
const isIndeterminate = ref(false);
const columnCount = ref(2);
const settingDialogVisible = ref(false);
const currentParam = ref<typeof props.params[0] | null>(null);

watch(
  () => props,
  (newVal) => {
    console.log(toRaw(newVal));
    columns.value = newVal.columns;
    selectedColumns.value = newVal.columns.map(col => col.val);
    iotData.value = newVal.data;
    currentRow.value.productKey = newVal.params.productKey;
    total.value = newVal.total;



  },{
    deep:true, immediate: true
  }
);

// name:"1760429782003000"
// seriesId:"\u0000m1_test\u00000"
// seriesIndex:0
// seriesName:"m1_test"
const handlePointClick = (arg: any) => {
  console.log('点击了图表上的点:', arg);
  currentRow.value.deviceNo = arg.seriesName;
  currentRow.value.sampletime = Number(arg.name);
  showDrawer.value = true ;
};

// 计算选中的参数映射
const selectedColumnsMap = computed(() => {
  return columns.value.filter((param) =>
    selectedColumns.value.includes(param.val)
  );
});

// 全选处理
const handleAllChange = (value: boolean) => {
  isIndeterminate.value = false;
  if (value) {
    selectedColumns.value = columns.value.map((param) => param.val);
  } else {
    selectedColumns.value = [];
  }
};

// 单个 checkbox 变化处理
const handleItemChange = () => {
  const total = columns.value.length;
  const selected = selectedColumns.value.length;
  allSelected.value = selected === total;
  isIndeterminate.value = selected > 0 && selected < total;
};

// 打开设置弹窗
const openSettingDialog = (param: typeof props.params[0]) => {
  // 创建参数的深拷贝，避免直接修改原始数据
  currentParam.value = { ...param };
  settingDialogVisible.value = true;
};

// 保存设置
const saveSettings = () => {
  if (!currentParam.value) return;

  // 找到并更新对应的参数
  const index = columns.value.findIndex(
    (param) => param.val === currentParam.value?.val
  );

  if (index !== -1) {
    columns.value[index] = { ...currentParam.value };
    ElMessage({
      message: t('datacenter.iotdataPage.settingSaved'),
      type: 'success'
    });
  }

  settingDialogVisible.value = false;
};

</script>

<style scoped lang="scss">
.data-chart-container {
  width: 100%;
  padding: 3px;
  box-sizing: border-box;
}

.control-panel {
  display: flex;
  gap: 15px;
  margin-bottom: 20px;
  padding-bottom: 20px;
  border-bottom: 1px solid #eaeaea;
}

.dropdown-control {
  .el-dropdown-link {
    display: flex;
    align-items: center;
    cursor: pointer;
  }
}

.checkbox-dropdown {
  width: 200px;
  padding: 10px;
}

.param-checkbox {
  margin-right: 10px;
}

.column-selection {
  display: flex;
  align-items: center;
  gap: 10px;
}

.selection-label {
  font-weight: 500;
}

.radio-group {
  display: flex;
  gap: 15px;
}

.cards-container {
  display: grid;
  gap: 20px;
  width: 100%;
}

.data-card {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.card-title {
  font-weight: 500;
}

.card-content {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px 0;
}

.setting-form {
  padding: 10px 0;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

@media (max-width: 768px) {
  .control-panel {
    flex-direction: column;
    gap: 15px;
  }

  .checkbox-group {
    flex-direction: column;
    gap: 10px;
  }

  .radio-group {
    flex-direction: column;
    gap: 10px;
  }
}

.chart-container {
  width: 100%;
  height: 220px;
}

/* 新增：多选框垂直排列样式 */
.vertical-checkbox-group {
  padding: 5px 15px; /* 与全选框对齐 */
}

.vertical-checkbox-item {
  display: block; /* 每个选项占一行 */
  margin: 8px 0; /* 垂直间距 */
}

/* 修复下拉菜单最大高度和滚动 */
.checkbox-dropdown {
  width: 220px;
  max-height: 300px; /* 限制高度 */
  overflow-y: auto; /* 内容过多时显示滚动条 */
  padding: 5px 0;
}
</style>
